package com.gis.halodepok;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.Toast;

public class WisataDepok extends ListActivity {
	public static final int MENU_CALL = 1;
	public static final int MENU_GPS = 2;
	public static final int MENU_BUKA = 3;

	@Override
	public boolean onContextItemSelected(MenuItem menu) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menu
				.getMenuInfo();
		int pos = info.position;
		Item item = ((AdapterItem) getListView().getAdapter()).getList()[pos];
		int menuid = menu.getItemId();
		if (menuid == MENU_CALL) {
			if (item.getTelp() != null) {
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ item.getTelp()));
				startActivity(intent);
			} else {
				Toast.makeText(this, "Tidak Ada No Telepon", Toast.LENGTH_SHORT)
						.show();
			}
		} else if (menuid == MENU_GPS) {

			Intent intent = new Intent(Intent.ACTION_VIEW,
					Uri.parse("http://maps.google.com/?f=d&saddr=&daddr="
							+ item.getLat() + "," + item.getLon() + " ("
							+ item.getNama() + ")"));
			startActivity(intent);
		} else if (menuid == MENU_BUKA) {
			AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

			// set the message to display
			alertbox.setMessage("Senin-Jum'at \n08.00-16.00" + item.getBuka());

			// add a neutral button to the alert box and assign a click listener
			alertbox.setNeutralButton("Ok",
					new DialogInterface.OnClickListener() {

						// click listener on the alert box
						public void onClick(DialogInterface arg0, int arg1) {

						}
					});

			// show it
			alertbox.show();
		}

		// TODO Auto-generated method stub
		return super.onContextItemSelected(menu);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(Menu.NONE, MENU_CALL, Menu.NONE, "Telepon");
		menu.add(Menu.NONE, MENU_GPS, Menu.NONE, "Navigasi");
		menu.add(Menu.NONE, MENU_BUKA, Menu.NONE, "Jam Buka");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ArrayList<Item> items = readfilexml();
		Item[] list = new Item[items.size()];
		for (int i = 0; i < items.size(); i++) {
			list[i] = items.get(i);
		}

		LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location networklocation = manager
				.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
		Location gpslocation = manager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		Location mylocation = null;
		if (networklocation != null) {
			mylocation = networklocation;
			if (gpslocation != null
					&& gpslocation.getTime() > networklocation.getTime()) {
				mylocation = gpslocation;
			}
		} else if (gpslocation != null) {
			mylocation = gpslocation;
		}
		setContentView(R.layout.listmenu);
		AdapterItem adapter = new AdapterItem(this, R.layout.list, list,
				mylocation);
		setListAdapter(adapter);
		((AdapterItem) adapter).sortByNameAsc();
		registerForContextMenu(getListView());
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) { 
	    openContextMenu(v);
	}

	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_NAMA = "nama";
	static final String KEY_ALAMAT = "alamat";
	static final String KEY_BUKA = "buka";
	static final String KEY_TELP = "telp";
	static final String KEY_LAT = "lat";
	static final String KEY_LONG = "long";

	public Document getDomElement(String xml) {
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (SAXException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		} catch (IOException e) {
			Log.e("Error: ", e.getMessage());
			return null;
		}
		// return DOM
		return doc;
	}

	public String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return this.getElementValue(n.item(0));
	}

	public final String getElementValue(Node elem) {
		Node child;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (child = elem.getFirstChild(); child != null; child = child
						.getNextSibling()) {
					if (child.getNodeType() == Node.TEXT_NODE) {
						return child.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	public ArrayList<Item> readfilexml() {
		ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
		ArrayList<Item> items = new ArrayList<Item>();
		Document doc = getDomElement(readFromFile());

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value

			Item item = new Item(getValue(e, KEY_NAMA),
					getValue(e, KEY_ALAMAT), getValue(e, KEY_TELP), "",
					Double.parseDouble(getValue(e, KEY_LAT)),
					Double.parseDouble(getValue(e, KEY_LONG)));
			items.add(item);

			map.put(KEY_NAMA, getValue(e, KEY_NAMA));
			map.put(KEY_ALAMAT, getValue(e, KEY_ALAMAT));
			map.put(KEY_TELP, getValue(e, KEY_TELP));
			map.put(KEY_LAT, getValue(e, KEY_LAT));
			map.put(KEY_LONG, getValue(e, KEY_LONG));

			// adding HashList to ArrayList
			System.err.println(map.get(KEY_NAMA) + "|" + map.get(KEY_ALAMAT));
			menuItems.add(map);
		}
		return items;
	}

	private String readFromFile() {

		String ret = "";

		try {
			File root = this.getDir("haha", Context.MODE_PRIVATE);

			File dir = new File(root.getAbsolutePath() + "/xmls/26.xml");
			FileInputStream inputStream = new FileInputStream(dir);
			if (inputStream != null) {
				InputStreamReader inputStreamReader = new InputStreamReader(
						inputStream);
				BufferedReader bufferedReader = new BufferedReader(
						inputStreamReader);
				String receiveString = "";
				StringBuilder stringBuilder = new StringBuilder();

				while ((receiveString = bufferedReader.readLine()) != null) {
					stringBuilder.append(receiveString);
				}

				inputStream.close();
				ret = stringBuilder.toString();

			}
		} catch (FileNotFoundException e) {
			Log.e("login activity", "File not found: " + e.toString());
		} catch (IOException e) {
			Log.e("login activity", "Can not read file: " + e.toString());
		}

		return ret;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}